/**
 * Created by wangguoqing on 2017/12/21.
 */
var params = new Object();
var role = null;
var setOrgCode = null;   //设置好的机构编码
var setOrgName = null;   //设置好的机构名称
var setOrgRoles = [];    //设置完成的机构角色信息，用于界面间的传值
params.validMark = 1;//有效标志
var url = path + "/system/assignPermission/listRoleByPage";
var li = '<li id="li{0}" data-id="{0}"><a href="#" onclick="deleteRole(this);"><img src="/resource/images/system/deleteBtn.png" alt=""></a><div class="name">{1}</div></li>'
var roleData = getGlobalVariable("role");
var datas = [];//定义数据
$(function () {
    //设置AjaxLoading
    setAjaxLoading();
    var grid = $("#tt");
    initGrid(grid);

    if (roleData.isJSON()) {
        role = JSON.parse(roleData)[0].roleDtos;
        setOrgCode = JSON.parse(roleData)[0].orgCode;
        setOrgName = JSON.parse(roleData)[0].orgName;
        $('#orgCode').val(setOrgCode);
        $('#orgName').val(setOrgName);
        document.getElementById("orgName").disabled = "disabled";
    } else {
        role = [];
    }
    setUserRole();
    /**
     * 搜索下拉列表
     **/
    $('#orgName').bind('input propertychange',
        function () {
            var inputValue = $('#orgName').val();
            datesValue(inputValue);
        });
});

//输入值查库模糊匹配
function datesValue(inputValue) {
    var param = new Object();
    param.orgName = inputValue;
    //根据 inputValue 查库
    $.ajax({
        type: "POST",
        url: path + '/system/user/queryOrgByList',
        dataType: "json",
        data: param,
        success: function callback(data) {
            var analyMsg = data;
            if (analyMsg.code != '0000') {
                $.messager.alert('操作提示', analyMsg.msg, 'info', function () {
                });
            } else {
                datas = analyMsg.returnObject.rows;
                _initItems(datas);
            }
        },
        error: function (data) {
            $.messager.alert('操作提示', data.responseText, 'error', function () {
            });
        }
    });

}

var maxFontNumber = 0;//最大字数
var suggestContainer = $('<div></div>'); //创建一个子<div>
suggestContainer.attr('id', "orgName-suggest");
suggestContainer.attr('tabindex', '0');
suggestContainer.hide();

//2：初始化搜索到的数据进行显示
var _initItems = function (items) {
    $('#orgCode').val("");
    suggestContainer.empty();
    for (var i = 0; i < items.length; i++) {
        if (items[i].orgName.length > maxFontNumber) {
            maxFontNumber = items[i].orgName.length;
        }
        var suggestItem = $('<div></div>'); //创建一个子<div>
        suggestItem.attr('orgCode', items[i].orgCode);
        suggestItem.append(items[i].orgName);
        suggestItem.css({
            'padding': '3px',//item间距
            'white-space': 'nowrap',
            'cursor': 'pointer',
            'background-color': 'RGB(199,237,204)',//默认背景颜色
            'color': '#000000'//默认字体颜色
        });
        suggestItem.bind("mouseover",
            function () {
                $(this).css({
                    'background-color': '#C9302C',//选中背景颜色
                    'color': '#ffffff'//选中字体颜色
                });
            });
        suggestItem.bind("mouseout",
            function () {
                $(this).css({
                    'background-color': 'RGB(199,237,204)',//默认背景颜色
                    'color': '#000000'//默认字体颜色
                });
            });
        suggestItem.bind("click", showClickTextFunction);//选中后处理数据
        //suggestItem.bind("click", itemSelectFunction);
        suggestItem.appendTo(suggestContainer);
        suggestContainer.appendTo(document.body);
    }
    suggestContainer.removeAttr("style");
    suggestContainer.css({
        'border': '1px solid #ccc',
        'max-height': '200px',
        'top': $('#orgName').offset().top + $('#orgName').outerHeight(),
        'left': $('#orgName').offset().left,
        'width': 12 * maxFontNumber + 2 * 3 + 30,
        'position': 'absolute',
        'font-size': '12px',//默认字体大小
        'font-family': 'Arial',
        'z-index': 99999,
        'background-color': '#FFFFFF',
        'overflow-y': 'auto',
        'overflow-x': 'hidden',
        'white-space': 'nowrap'

    });
    maxFontNumber = 0;
    suggestContainer.show();
};

//3.选中后处理数据
var showClickTextFunction = function () {
    //alert(this.innerText + "---" + this.getAttribute("orgCode"));
    $('#orgName').val(this.innerText);
    $('#orgCode').val(this.getAttribute("orgCode"));
    suggestContainer.hide();
};

//设置已选角色
function setUserRole() {
    var html = "";
    var strName = "";
    var strIds = "";
    $.each(role, function (i, v) {
        html += String.format(li, v.roleId, v.roleName);
        if (i == 0) {
            strIds += v.roleId;
            strName += v.roleName;
        } else {
            strIds += "," + v.roleId;
            strName += "," + v.roleName;
        }
    });
    $("#membersList").html(html);
    $("#roles").val(strName);
    $("#rolesIds").val(strIds);


}

function deleteRole(obj) {
    $.each(role, function (i, v) {
        if (v.roleId == $(obj).parent().attr("data-id")) {
            role.splice(i, 1); //删除
            return false;
        }
    });
    $(obj).parent().remove();
    var rows = $('#tt').datagrid('getRows');//获得行
    for (var i = 0; i < rows.length; i++) {
        if (rows[i].roleId == $(obj).parent().attr("data-id")) {
            $('#tt').datagrid('unselectRow', i);//取消选择
        }
    }
}

//初始化表格和数据
function initGrid(grid) {
    var columns = [
        {
            field: "roleId",
            title: "ID",
            hidden: true,
            align: "left",
            sortable: false,
            resizable: true,
            width: 80
        },
        {
            field: "roleCode",
            title: "角色代码",
            align: "center",
            halign: "center",
            sortable: false,
            resizable: true,
            width: 80
        },
        {
            field: "roleName",
            title: "角色名称",
            align: "center",
            halign: "center",
            sortable: false,
            resizable: true,
            width: 140
        }
    ];

    initPageGridWithCheckBox(grid, params, url, columns, "#tb", "roleId");
    var gridOptions = $("#tt").datagrid("options");
    gridOptions.onLoadSuccess = function (data) {
        $('#tt').datagrid("fixRownumber");
        $.each(role, function (i, v) {
            $.each(data.rows, function (index, val) {
                if (v.roleId == val.roleId) {
                    $("#tt").datagrid("selectRow", index);
                    setUserRole();
                }
            });
        });
    };
    gridOptions.onCheck = function (index, row) { //单击选中
        var f = true;
        $.each(role, function (i, v) {
            if (v.roleId == row.roleId) {
                f = false;
            }
        });
        if (f) {
            role.push(row);
            setUserRole();
        }
    };
    gridOptions.onUncheck = function (index, row) { //单击取消选中
        $.each(role, function (i, v) {
            if (v.roleId == row.roleId) {
                role.splice(i, 1); //删除
                return false;
            }
        });
        setUserRole();
    };
    gridOptions.onCheckAll = function (rows) { //单击全选
        $.each(rows, function (index, row) {
            var f = true;
            $.each(role, function (i, v) {
                if (v.roleId == row.roleId) {
                    f = false;
                }
            });
            if (f) {
                role.push(row);
            }
        });
        setUserRole();
    };
    gridOptions.onUncheckAll = function (rows) { //取消全选
        $.each(rows, function (index, row) {
            $.each(role, function (i, v) {
                if (v.roleId == row.roleId) {
                    role.splice(i, 1); //删除
                    return false;
                }
            });
        });
        setUserRole();
    };
    getPage(grid, params, url);
}

function submit_Add() {
    var setRolesArray = new Array();     //设置的角色名称数组
    var param = new Object();
    var roles = $('#roles').val();
    var orgName = $('#orgName').val();
    var orgCode = $('#orgCode').val();

    //判断机构不为空
    if (orgName == "undefined" || orgName == "null" || orgName == null || orgName == "") {
        $.alert("default", "error", "设置机构名称不能为空！");
        return;
    }
    if (orgCode == "undefined" || orgCode == "null" || orgCode == null || orgCode == "") {
        $.alert("default", "error", "设置机构编码不能为空！");
        return;
    }
    //判断设置角色 roles
    if (roles == "undefined" || roles == "null" || roles == null || roles == "") {
        $.alert("default", "error", "设置角色不能为空！");
        return;
    }

    var roleNameParams = new Object();
    var roleNames = $("#roles").val();
    var roleIds = $("#rolesIds").val();
    roleNameParams.roleNames =roleNames;
    //做一个互斥校验
    $.ajax({
        type: "POST",
        url: path + '/system/user/queryMutexByRoleNames',
        dataType: "json",
        data: roleNameParams,
        success: function callback(data) {
            var analyMsg = data;
            if (analyMsg.code != '0000') {
                $.messager.alert('操作提示', analyMsg.msg, 'info', function () {
                });
                return;
            } else {
                //互斥校验通过后
                param.id = orgCode;
                param.orgName = orgName;
                param.orgCode = orgCode;
                param.userId = $("#userId").val()
                param.roleIds = roleIds;
                var resultRoleNames = roleNames.split(",");
                var resultRoleIds = roleIds.split(",");
                if (resultRoleIds.length == resultRoleNames.length) {
                    for (var i = 0; i < resultRoleIds.length; i++) {
                        var roleNameParams = new Object();
                        roleNameParams.roleName = resultRoleNames[i];
                        roleNameParams.roleId = resultRoleIds[i];
                        setRolesArray.push(roleNameParams);
                    }
                }
                param.roleDtos = JSON.stringify(setRolesArray);
                setOrgRoles.push(param);
                setGlobalVariable("setOrgRoles", JSON.stringify(setOrgRoles));
                closeLayer();
            }
        },
        error: function (data) {
            $.messager.alert('操作提示', data.responseText, 'error', function () {
            });
            return;
        }
    });

}

/**
 * 传入两个数组作为参数，寻找两个数组中的相同元素。
 * @param a
 * @param b
 * @returns {Array}
 * @constructor
 */
function FilterData(a, b) {
    //循环判断数组a里的元素在b里面有没有，有的话就放入新建立的数组中
    var result = new Array();
    var c = b.toString();
    for (var i = 0; i < a.length; i++) {
        if (c.indexOf(a[i].toString()) > -1) {
            for (var j = 0; j < b.length; j++) {
                if (a[i] == b[j]) {
                    result.push(a[i]);
                    break;
                }
            }
        }
    }
    return result;
}

